<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2021/12/13
 * Time: 9:47
 */

namespace app\admin\controller;


use think\Db;

class Classcode extends Base
{
    /**
     * 课程兑换码列表
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax ()){
            $cc_code = trim(input('cc_code'));
            $cc_is_use = input('cc_is_use');
            $where = [];
            if(isset($cc_code) && $cc_code != ''){
                $where['cc_code'] = ['like', '%' . $cc_code . '%'];
            }
            if(isset($cc_is_use) && $cc_is_use != ''){
                $where['cc_is_use'] = $cc_is_use;
            }
            
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 100;
            $count = Db::name('class_code')
                ->join('up_u_user', 'user_id = cc_use_user_id', 'LEFT')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::name('class_code')
                ->join('up_u_user', 'user_id = cc_use_user_id', 'LEFT')
                ->where($where)
                ->field('cc_id, cc_code, user_username, cc_is_use, cc_use_time')
                ->order('cc_is_use asc, cc_use_time desc')
                ->page($Nowpage,$limits)
                ->select();
        
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch();
    }
    
    /**
     * 生成课程兑换码
     * @return \think\response\Json
     */
    public function createClassCode(){
        $code = randCharForClassCode(8);
        $res = Db::table('up_class_code')->insert(['cc_code' => $code]);
        if($res){
            return json(['code' => 200, 'msg' => '生成成功']);
        }else{
            return json(['code' => 100, 'msg' => '生成失败']);
        }
    }
}